<?php

namespace app\health\controller;

use app\common\library\time\TimeHelper;
use app\health\model\fanqudao\CouponSend;
use app\health\model\HealthBusiness;
use app\health\model\HealthBusinessAccess;
use app\health\model\HealthFuluActivity;
use app\health\model\HealthFuluGoods;
use app\health\model\HealthFuluOrder;
use app\health\model\HealthPayment;
use app\health\model\healthPro\Callback;
use app\health\model\healthPro\Interests;
use app\health\model\healthPro\TvCallbackLog;
use app\health\model\healthPro\TvOrderGrant;
use app\health\model\healthPro\TvProduct;
use app\health\model\healthPro\TvUserCard;
use app\health\model\healthPro\UserEquity;
use app\health\model\HealthUser;
use app\health\model\MasterUser;
use app\health\model\tracking\HealthTrackingHealth;
use app\health\service\BusinessService;
use app\health\service\EquityCenterService;
use app\health\service\PajkService;
use app\health\service\WeMiniService;
use app\health\service\WePayService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use think\Cache;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

class Equity extends ApiBase
{

    protected $noNeedLogin = ['service_list', 'exclusive', 'judge_server', 'send_code', 'get_business_code', 'promote_transact', 'business_access', 'business_notify'];

    /**
     * 会员专属福利
     * @return void
     */
    public function exclusive(): void
    {
        $isVip      = $this->auth ? EquityCenterService::isPajkVip($this->auth->mobile) : 0;
        $tips       = [
            '领取后，权益将发到登录该小程序的手机账号内，请确认该手机号与对应第三方APP绑定账号一致',
            '确认领取后，该权益无法退还',
            '高峰期间，将延迟5-30分钟到账',
        ];
        $equity_one = [
            'title' => '平安健康',
            'items' => [
                '免费问诊', '协助就医', '专家二诊', '免费流量'
            ]
        ];
        $fuluGoods  = HealthFuluGoods::where('type', 1)->where('status', 1)->column('id,name,icon,must_element');
        sort($fuluGoods);
        $equity_two = [
            'title' => '会员周卡',
            'items' => $fuluGoods
        ];
        $this->success('success', [
            'is_vip'     => $isVip,
            'tips'       => $tips,
            'equity_one' => $equity_one,
            'equity_two' => $equity_two
        ]);
    }

    /**
     * 领取专属福利
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \RedisException
     * @throws \think\Exception
     */
    public function get_exclusive(): void
    {
        if (Cache::store('redis')->has('equity_get_exclusive:' . md5($this->auth->mobile))) {
            $this->error('请不要频繁请求');
        }
        Cache::store('redis')->set('equity_get_exclusive:' . md5($this->auth->mobile), 1, 5);
        $fuluGoodsId = $this->request->param('id');
        $fuluGoods   = HealthFuluGoods::where('id', $fuluGoodsId)->where('type', 1)->where('status', 1)->find();
        if (!$fuluGoods) {
            $this->error('权益不存在');
        }
        if (!EquityCenterService::isPajkVip($this->auth->mobile)) {
            $this->error('您还不是会员');
        }
        //查询本月是否已领取
        $isGet = HealthFuluOrder::whereTime('created_at', 'month')->where('user_id', $this->auth->id)->where('type', 1)->count();
        if ($isGet > 0) {
            $this->error('您本月已领取权益');
        }
        $order     = HealthFuluOrder::create([
            'type'           => 1,
            'order_no'       => create_trade_no('F'),
            'user_id'        => $this->auth->id,
            'total_price'    => 0,
            'pay_price'      => 0,
            'discount_price' => 0,
        ]);
        $orderItem = [
            [
                'goods_id'       => $fuluGoodsId,
                'goods_name'     => $fuluGoods['name'],
                'goods_code'     => $fuluGoods['goods_code'],
                'account'        => $this->auth->mobile,
                'price'          => 0,
                'discount_price' => 0,
                'original_price' => 0,
                'cost_price'     => 0,
            ]
        ];
        $order->orderItem()->saveAll($orderItem);
        HealthFuluOrder::paySuccess($order['order_no']);
        $this->success('领取成功', [
            'equity' => [
                [
                    'name' => '平安健康',
                    'icon' => 'https://xinquanyu.oss-cn-beijing.aliyuncs.com/40/4a084fcea61b65f4bc54db35a4804c.png'
                ],
                [
                    'name' => $fuluGoods['name'],
                    'icon' => $fuluGoods['icon'],
                ]
            ]
        ]);
    }

    /**
     * 平安健康服务列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function service_list(): void
    {
        $this->success('success', PajkService::serviceList());
    }

    /**
     * 我的权益卡
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function card(): void
    {
        //1=待使用,2=已过期
        $status    = $this->request->param('status/d', 1);
        $where     = ['server_num' => ['=', $this->auth->mobile]];
        $serveIden = '';//平安健康服务类型
        if ($status === 1) {
            $where['expire_time'] = ['>', time()];
        } else {
            $where['expire_time'] = ['<', time()];
        }
        if ($this->request->has('type')) {
            $serveIden = PajkService::getServiceByType($this->request->param('type'))['iden'] ?? '';
        }
        // 查询订购权益
        $callbackQuery = Callback::where($where)
            ->with(['product', 'interests.tvProduct'])
            ->cache(true, 60)
            ->field('id,pid,is_receive,expire_time,sku_code,server_num,sku_name,bus_code');
        if ($status === 1) {
            $callbackLists = $callbackQuery->order('is_receive desc')->select();
        } else {
            $callbackLists = $callbackQuery->limit(3)->order('id desc')->select();
        }
        $callbackLists = collection((array)$callbackLists)->toArray();

        foreach ($callbackLists as $key => &$item) {
            $product = $item['product'] ?: [];
            if (!empty($product)) {
                $item['sku_name'] = $product['name'] ?? '';
            }
            if ($serveIden && !isset($item['interests']['tv_product']['content'][$serveIden]) && ($serveIden !== 'sjzx')) {
                unset($callbackLists[$key]);
            }
            unset($item['pid'], $item['product'], $item['interests']);
        }
        //查找电信或者年卡的订单
        $otherQuery = UserEquity::where([
            'mobile'   => ['=', $this->auth->mobile],
            'end_time' => $status === 1 ? ['>', time()] : ['<', time()],
        ])->cache(true, 60)->with(['interests.tvProduct'])->select();
        $other      = collection((array)$otherQuery)->toArray();
        foreach ($other as $key => &$item) {
            $interests            = $item['interests'] ?: [];
            $item['sku_name']     = $interests['name'] ?? '';
            $item['product_code'] = $interests['product_code'] ?? '';
            $item['is_receive']   = 2;
            if ($serveIden && !isset($item['interests']['tv_product']['content'][$serveIden])) {
                unset($callbackLists[$key]);
            }
            unset($item['interests']);
        }
        $local    = [];
        $activity = HealthFuluActivity::where('mobile', $this->auth->mobile)->cache(true, TimeHelper::secondEndToday())->find();
        if ($activity && $activity['active_state'] === 0) {
            //创建订单
            $activity->save(['is_register' => 1, 'active_state' => 1]);
            $order     = HealthFuluOrder::create([
                'type'       => 3,
                'order_no'   => empty($activity['order_no']) ? create_trade_no('F') : $activity['order_no'],
                'user_id'    => $this->auth->id,
                'pay_time'   => time(),
                'pay_status' => 1,
            ]);
            $fuluGoods = HealthFuluGoods::where('id', $activity['fulu_goods_id'])->find();
            $order->orderItem()->save([
                'goods_id'       => $activity['fulu_goods_id'],
                'goods_name'     => $fuluGoods['name'] ?? '',
                'goods_code'     => $fuluGoods['goods_code'] ?? '',
                'account'        => $activity['account'],
                'price'          => 0,
                'discount_price' => 0,
                'original_price' => 0,
                'cost_price'     => 0,
            ]);
        }
        if ($status === 1 && HealthFuluOrder::where('user_id', $this->auth->id)->where('pay_status', 1)->count() > 0) {
            $local[] = [
                'id'         => -1,
                'start_time' => 0,
                'end_time'   => 0,
                'sku_name'   => '互联网权益'
            ];
        }
        // 查询泛渠道卡券
//	    if(CouponSend::where('mobile',$this->auth->mobile)->where('distr_month',date('Y-m'))->count()>0){
//		    $local[] = [
//			    'id'         => -2,
//			    'start_time' => 0,
//			    'end_time'   => 0,
//			    'sku_name'   => '微信代金券'
//		    ];
//	    }
        $data = [
            'order'       => $status === 1 ? $callbackLists : [],
            'expire'      => $status === 2 ? $callbackLists : [],
            'other'       => $status === 1 ? $other : [],
            'otherExpire' => $status === 2 ? $other : [],
            'local'       => $local,
        ];
        $this->success('success', $data);
    }

    /**
     * 权益卡服务列表
     * Undocumented function
     * @Author 张旭鹏
     * @DateTime 2023-07-21
     */
    public function card_serve(): void
    {
        $id         = $this->request->param('id');
        $serve_type = $this->request->param('serve_type/d', 1);
        if (empty($serve_type)) {
            $this->error('请选择服务类型');
        }
        $is_receive = 2;
        if ($serve_type === 2) {//电信或年卡
            $info = UserEquity::where('id', $id)->field('id,sku_code,end_time,type')->find();
        } else {
            $info       = Callback::where('id', $id)->field('id,is_receive,expire_time,sku_code,server_num,sku_name,pid')->find();
            $is_receive = $info['is_receive'];
        }
        if (!$info) {
            $this->error('您还没有办理相关业务');
        }
        $info = $info->toArray();
        //获取平安健康产品库用户信息
        $masterUserInfo       = MasterUser::where('mobile', $this->auth->mobile)->find();
        $interestsInfo        = Interests::where('sku_code', $info['sku_code'])->find();
        $info['product_code'] = $interestsInfo['product_code'];
        $productCode          = $interestsInfo['product_code'];
        //判断该订单是否充值过
        $serve = [];
        if ((int)$is_receive === 1) {
            //未充值
            $info['is_receive'] = 1;
            $con                = TvProduct::where('product_code', $productCode)->find();
            $contentList        = TvUserCard::getContentList($con['content'], $con['product_code']);
        } else {
            $card = TvUserCard::where('mobile', $this->auth->mobile)
                ->where('product_code', $productCode)
                ->where('openid', $masterUserInfo['third_id'])
                ->where('serviceexpireat', '>', time())
                ->find();
            if ($card) {
                $info['is_receive'] = 2;
                $contentList        = TvUserCard::getContentList($card['content'], $card['product_code']);
            } else {
                $info['is_receive'] = 1;
                $con                = TvProduct::where('product_code', $productCode)->find();
                $contentList        = TvUserCard::getContentList($con['content'], $con['product_code']);
            }
        }
        $serve       += $contentList;
        $contentList = [];
        $card        = TvUserCard::where('mobile', $this->auth->mobile)
            ->where('product_code', 'XQY_SSYD')
            ->where('openid', $masterUserInfo['third_id'])
            ->where('serviceexpireat', '>', time())
            ->find();
        if ($card) {
            $contentList = TvUserCard::getContentList($card['content'], $card['product_code']);
        } else if ($serve_type === 1 && (!empty($info['pid']) && in_array((int)$info['pid'], [2, 24, 25]))) {
            $con         = TvProduct::where('product_code', 'XQY_SSYD')->find();
            $contentList = TvUserCard::getContentList($con['content'], $con['product_code']);
        }
        $serve         = array_merge($serve, $contentList);
        $info['serve'] = $serve;
        $this->success('成功', $info);
    }

    /**
     * 使用服务
     * @return void
     */
    public function use_serve(): void
    {
        $params   = $this->request->param();
        $idCard   = $this->auth->id_card;
        $realName = $this->auth->real_name;
        try {
            if (empty($idCard) || empty($realName)) {
                throw new Exception('请先添加就诊人信息');
            }
            if (empty($params['serve_type'])) {
                throw new Exception('请选择服务类型');
            }
            $type = (int)($params['type'] ?? 0);//使用的平安健康服务类型
            if (!$type) {
                throw new Exception('服务类型不存在');
            }
            $pajkServe = PajkService::getServiceByType($type);
            if (empty($pajkServe)) {
                throw new Exception('平安健康权益不存在');
            }
            // 1=移动业务,2=电信或年卡
            $serveType = (int)$params['serve_type'];
            if ($serveType === 2) {//电信或年卡
                $info = UserEquity::where('id', $params['id'])
                    ->field('id,sku_code,end_time,type,bus_code,type,pid')
                    ->find();
            } else {
                $info = Callback::where('id', $params['id'])
                    ->field('id,is_receive,expire_time,sku_code,server_num,sku_name,pid,bus_code')
                    ->find();
            }
            //查询订单信息
            if (!$info) {
                throw new Exception('您还没有办理相关业务');
            }
            //查找健康权益用户数据
            $masterUserInfo = MasterUser::where('mobile', $this->auth->mobile)->find();
            //查找订购的是那个权益
            $interestsInfo = Interests::with(['tvProduct'])->where('sku_code', $info['sku_code'])->find();
            if ($serveType === 2) {//电信或年卡
                if (!isset($interestsInfo['tvProduct']['content'][$pajkServe['iden']])) {
                    throw new Exception('该卡不存在此权益');
                }
            } else {
                if (!isset($interestsInfo['tvProduct']['content'][$pajkServe['iden']]) && (int)$pajkServe['type'] !== 11 && (int)$pajkServe['type'] !== 10) {
                    throw new Exception('该卡不存在此权益');
                }
                if (((int)$pajkServe['type'] === 11 || (int)$pajkServe['type'] === 10) && !in_array((int)$info['pid'], [2, 24, 25])) {
                    throw new Exception('暂无健身权益');
                }
            }
            //查询该权益下是否存在所请求的服务类型
            $tvUserCardWhere = [
                'mobile' => $this->auth->mobile,
                'openid' => $masterUserInfo['third_id'],
            ];
            //根据使用服务类型type 构建充值记录查询条件
            if ($serveType === 1) {
                //移动业务
                if ($type === 11 || $type === 10) {
                    //私教1v1
                    $tvUserCardWhere['product_code'] = 'XQY_SSYD';
                } elseif ($interestsInfo['type'] === 3 && $type === 1) {//连续包月
                    $tvUserCardWhere['product_code'] = ['in', 'XQY_ELBYX_A,XQY_YOUXIANG'];
                } else {
                    $tvUserCardWhere['product_code'] = $interestsInfo['product_code'];
                    $tvUserCardWhere['callback_id']  = $info['id'];
                }
            } elseif ($serveType === 2) {
                if ($type === 11 || $type === 10) {
                    $tvUserCardWhere['product_code'] = 'XQY_SSYD';
                } elseif ($interestsInfo['type'] === 3 && $type === 1) {
                    $tvUserCardWhere['product_code'] = 'XQY_ELBYX_A';
                } else {
                    $tvUserCardWhere['product_code'] = $interestsInfo['product_code'];
                }
            } else {
                throw new Exception('非法操作');
            }
            //查询对应充值记录
            $row = TvUserCard::where($tvUserCardWhere)
                ->whereTime('serviceexpireat', '>', time())
                ->order('id', 'desc')
                ->find();
            if (!$row && !empty($tvUserCardWhere['callback_id']) && !empty($info['is_receive']) && (int)$info['is_receive'] === 2) {
                unset($tvUserCardWhere['callback_id']);
                $row = TvUserCard::where($tvUserCardWhere)
                    ->whereTime('serviceexpireat', '>', time())
                    ->order('id', 'desc')
                    ->find();
            }
            //是否充值服务
            $isRechargeServe = false;
            //查询服务次数是否用尽
            if ($row) {
                $content = $row->content;
                foreach ($content as $key => $num) {
                    if (($key === $pajkServe['iden']) && $num <= 0) {
                        if ($interestsInfo['type'] === 3 && $type === 1) {
                            $isRechargeServe = true;
                            break;
                        }
                        throw new Exception('服务已用完');
                    }
                }
            }
            //判断此卡权益是否可充值
            if (!$row) {
                if ($interestsInfo['type'] !== 3 && $type !== 11 && $type !== 10) {
                    if ($serveType === 1 && $info['is_receive'] === 2) {
                        throw new Exception('该卡权益已过期');
                    }
                    if ($serveType === 2 && $info['end_time'] <= time()) {
                        throw new Exception('该卡权益已过期');
                    }
                }
                $isRechargeServe = true;
            }
            //未充值走充值接口
            if ($isRechargeServe) {
                $this->euqity($interestsInfo, $serveType, $type, $masterUserInfo, $info);
            }
            //生成平安健康token
            $ticket = EquityCenterService::getPajkToken($this->auth->mobile);
            if ($ticket === false) {
                throw new Exception('会员认证失败,请联系客服');
            }
            //生成小程序地址链接
            $page = PajkService::getPageUrl($type, $ticket['token']);
        } catch (Exception $exception) {
            if (!empty($params['tracking_row_id'])) {
                HealthTrackingHealth::where('id', $params['tracking_row_id'])
                    ->update(['error' => $exception->getMessage(), 'is_use' => 2]);
            }
            $this->error($exception->getMessage(), [], $exception->getCode());
        }
        $this->success('success', compact('page', 'ticket'));
    }

    /**
     * 平安健康权益充值
     * @param $interestsInfo
     * @param $serveType
     * @param $type
     * @param $userInfo
     * @param $callback
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function euqity($interestsInfo, $serveType, $type, $userInfo, $callback): void
    {
        $interestsType = $interestsInfo['type'];
        $directCharge  = true;//是否直充
        if ($type === 11 || $type === 10) {
            $interestsType                 = 1;
            $interestsInfo['product_code'] = 'XQY_SSYD';
        } elseif ($type === 1 && $interestsInfo['type'] === 3) {
            //健康管家去问诊就充值e疗宝A
            $interestsInfo['product_code'] = 'XQY_ELBYX_A';
        } elseif ($interestsInfo['type'] !== 1) {
            $directCharge = false;
        }
        if ($serveType === 2 && !empty($callback['type']) && $callback['type'] === 3) {
            $directCharge = true;
        }
        $genderMap        = ['男' => 'MALE', '女' => 'FEMALE'];
        $tvOrderGrantData = [
            'mobile'       => $userInfo['mobile'],
            'openid'       => $userInfo['third_id'],
            'name'         => $userInfo['name'],
            'gender'       => $genderMap[$userInfo['sex']] ?? 'OTHER',
            'id_type'      => 'IDENTITYCARD',
            'id_no'        => $userInfo['card'],
            'birthday'     => date('Ymd', strtotime($userInfo['birthday'])),
            'product_code' => $interestsInfo['product_code'],
            'order_no'     => 'M' . date('YmdHis') . str_pad(random_int(10000, 99999), 5, '0', STR_PAD_LEFT),
            'type'         => 2,
            'create_time'  => time(),
            'bus_code'     => $callback['bus_code'] ?? '',
            'pid'          => $callback['pid'] ?? 0,
            'isp'          => 2,
            'callback_id'  => $callback['id'],
        ];
        if (!$directCharge) {
            //查询是否有生成的订单
            $grantOrder = TvOrderGrant::where('type', 2)
                ->where('mobile', $userInfo['mobile'])
                ->where('openid', $userInfo['third_id'])
                ->where('product_code', $interestsInfo['product_code'])
                ->order('id desc')
                ->limit(1)
                ->find();
            if ($grantOrder) {
                //判断是不是一年之前订单
                $year = strtotime("+1 year", $grantOrder['activation_time'] / 1000);
                if (time() > $year && $grantOrder['state'] === 1) {
                    //添加订单
                    TvOrderGrant::create($tvOrderGrantData);
                    throw new Exception('实名认证审核中,48小时之后到账!');
                } else {
                    //判断是不是未发放并且是不是两天之前的订单
                    if ($grantOrder['status'] === 0 && $grantOrder['create_time'] + 172800 < time()) {
                        //往下走
                        $grantId = $grantOrder['id'];
                    } elseif ($grantOrder['status'] === 1) {
                        TvOrderGrant::create($tvOrderGrantData);
                        throw new Exception('实名认证审核中,48小时之后到账!');
                    } else {
                        throw new Exception('实名认证审核中,48小时之后到账!');
                    }
                }
            } else {
                TvOrderGrant::create($tvOrderGrantData);
                throw new Exception('实名认证审核中,48小时之后到账!');
            }
        } else {
            //生成之前先判断上一个订单是否给传过来回调数据了
            $isFind = TvOrderGrant::where('type', 2)
                ->where('mobile', $userInfo['mobile'])
                ->where('product_code', $interestsInfo['product_code'])
                ->order('id desc')
                ->limit(1)
                ->find();
            if ($isFind) {
                //判断上个订单是否充值成功
                if ($isFind['state'] === 1) {
                    //添加订单
                    $tvOrderGrant = TvOrderGrant::create($tvOrderGrantData);
                    $grantId      = $tvOrderGrant['id'];
                } else {
                    //未充值成功查看订单回调表是否有次订单
                    $find = TvCallbackLog::where('order_no', $isFind['order_no'])->find();
                    if ($find) {
                        //说明上个订单有返回状态
                        if (!$find['status'] == 1) {
                            throw new Exception('充值异常,请联系客服解决');
                        } else {
                            //生成发放订单
                            $tvOrderGrant = TvOrderGrant::create($tvOrderGrantData);
                            //添加订单
                            $grantId = $tvOrderGrant['id'];
                        }
                    } else {
                        $grantId = $isFind['id'];
                    }
                }
            } else {
                //生成发放订单
                //添加订单
                $tvOrderGrant = TvOrderGrant::create($tvOrderGrantData);
                $grantId      = $tvOrderGrant['id'];
            }
        }
        EquityCenterService::recharge($grantId, $type, $interestsType, $interestsInfo['product_code'], $callback['id']);
    }

    /**
     * 服务验证
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function serve_check()
    {
        $where     = [
            'server_num'  => ['=', $this->auth->mobile],
            'expire_time' => ['>', time()]
        ];
        $pajkServe = PajkService::getServiceByType($this->request->param('type', 0));
        if (empty($pajkServe)) {
            $this->error('平安健康权益不存在');
        }
        $serveIden = $pajkServe['iden'] ?? '';
        $is_vip    = $is_auth = 0;
        // 查询订购权益
        $callbackQuery = Callback::where($where)
            ->with(['product', 'interests.tvProduct'])
            ->field('id,pid,is_receive,expire_time,sku_code,server_num,sku_name,bus_code')
            ->order('is_receive desc')
            ->select();
        $callbackLists = collection((array)$callbackQuery)->toArray();
        foreach ($callbackLists as $item) {
            $is_vip = 1;
            if (isset($item['interests']['tv_product']['content'][$serveIden]) || ($serveIden === 'sjzx' && in_array((int)$item['pid'], [2, 24, 25]))) {
                $is_auth = 1;
            }
        }
        //查找电信或者年卡的订单
        $otherQuery = UserEquity::where([
            'mobile'   => ['=', $this->auth->mobile],
            'end_time' => ['>', time()],
        ])->with(['interests.tvProduct'])->select();
        $other      = collection((array)$otherQuery)->toArray();
        foreach ($other as $item) {
            $is_vip = 1;
            if (isset($item['interests']['tv_product']['content'][$serveIden])) {
                $is_auth = 1;
            }
        }
        $this->success('success', [
            'is_vip'  => $is_vip,
            'is_auth' => $is_auth
        ]);
    }

    /**
     * 判断当前用户是否会员
     * @Author 张旭鹏
     * @DateTime 2023-07-05
     */
    public function is_vip(): void
    {
        $this->success('success', ['is_order' => EquityCenterService::isPajkVip($this->auth->mobile)]);
    }

    /**
     * 判断订购那个业务
     * @Author 张旭鹏
     * @DateTime 2023-07-06
     */
    public function is_server(): void
    {
        //服务类型 1 问诊 3 挂号 4 二诊
        $type = $this->request->post('type', 1);

        $this->success('success', EquityCenterService::isServer($this->auth->mobile, $type));
    }

    /**
     * 判断订购那个业务
     * @Author 张旭鹏
     * @DateTime 2023-07-06
     */
    public function judge_server(): void
    {
        $mobile = $this->request->param('mobile');
        $type   = $this->request->post('type', 1);
        if (empty($mobile)) {
            $this->error('请输入手机号');
        }
        //服务类型 1 问诊 3 挂号 4 二诊
        $this->success('success', EquityCenterService::isServer($mobile, $type));
    }

    /**
     * 订购业务
     * @Author 张旭鹏
     * @DateTime 2023-07-06
     */
    public function transact(): void
    {
        //annual_card=年卡 operators=运营商
        $mode = $this->request->post('mode', 'annual_card');
        if ($mode === 'annual_card') {
            //创建年卡订单
            $healthAnnualCardOrder = EquityCenterService::orderAnnualCard($this->auth->mobile, MasterUser::getMasterUserId($this->auth->mobile));
            if (empty($healthAnnualCardOrder['order_no'])) {
                $this->error('订单创建失败');
            }
            // 创建支付订单
            $payment    = HealthPayment::create([
                'type'            => 1,
                'user_id'         => $this->auth->id,
                'order_no'        => $healthAnnualCardOrder['order_no'],
                'pay_description' => $healthAnnualCardOrder['interests_name'],
                'pay_way'         => HealthPayment::PAY_WAY_WECHAT,
                'pay_money'       => $healthAnnualCardOrder['pay_money'],
                'pay_status'      => 0
            ]);
            $pay_config = HealthPayment::createdWechatPay($payment, $this->auth->openid);
            if (empty($pay_config['prepay_id'])) {
                $this->error('微信支付创建失败');
            }
            $pay_config = WePayService::WePayOrder()->jsapiParams($pay_config['prepay_id']);
            $this->success('success', [
                'pay_config' => $pay_config,
                'payment_id' => $payment['id'],
                'pay_status' => $payment['pay_status']
            ]);
        }
        if ($mode === 'operators') {
            $mobile = $this->request->param('mobile', $this->auth->mobile);
            $code   = $this->request->param('code');
            $zfCode = $this->request->param('zfCode');
            $city   = $this->request->param('city');
            if (!$city) {
                $this->error('请传入城市编码');
            }
            $result = EquityCenterService::busHandle($mobile, $code, $zfCode, $city);
            if (isset($result['error_code'])) {
                $this->error($result['msg']);
            }
            $this->success('办理成功');
        }
        $this->error('不存在的业务模式');
    }

    /**
     * 业务办理页访问记录
     * @return void
     * @throws Exception
     */
    public function business_access(): void
    {
        $pid                  = $this->request->param('pid', 0);
        $platform             = $this->request->param('platform', '');
        $url                  = $this->request->param('url', '');
        $wxLoginCode          = $this->request->param('wx_login_code', '');
        $weSession            = WeMiniService::getWeLoginSession($wxLoginCode);
        $healthBusinessAccess = HealthBusinessAccess::create([
            'request_id' => create_trade_no('R'),
            'channel'    => $pid,
            'platform'   => $platform,
            'ip'         => $this->request->ip(),
            'url'        => $url,
            'created_at' => date('Y-m-d H:i:s')
        ]);
        $this->success('success', [
            'request_id' => $healthBusinessAccess['request_id'],
            'openid'     => $weSession['openid'] ?? '',
        ]);
    }

    /**
     * 获取业务订购短信验证码
     * @return void
     * @throws GuzzleException
     * @throws \JsonException
     */
    public function get_business_code(): void
    {
        $mobile    = $this->request->param('mobile', '');
        $zf_code   = $this->request->param('zf_code', '');
        $city_code = $this->request->param('city_code', '');
        if (empty($mobile) || !preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            $this->error('请输入正确的手机号');
        }
        if (empty($zf_code) || empty($city_code)) {
            $this->error('请求异常,请联系客服');
        }
        $result = BusinessService::sendCode(['mobile' => $mobile, 'zf_code' => $zf_code, 'city_code' => $city_code, 'ip' => $this->request->ip()]);
        if (is_array($result)) {
            $this->success('发送成功', ['order_no' => $result['order_no']]);
        }
        $this->error($result);
    }

    /**
     * 订购业务
     * @Author 张旭鹏
     * @DateTime 2023-07-06
     */
    public function promote_transact(): void
    {
        $request_id = $this->request->param('request_id', create_trade_no('R'));
        $mobile     = $this->request->param('mobile', '');
        $zf_code    = $this->request->param('zf_code');
        $pid        = $this->request->param('pid', 0);
        $platform   = $this->request->param('platform', '');
        $url        = $this->request->param('url', '');
        $code       = $this->request->param('code', '');
        $city_code  = $this->request->param('city_code', '');
        $order_no   = $this->request->param('order_no', '');
        $clickid    = $this->request->param('clickid', '');
        // 查询用户信息
        $wxLoginCode = $this->request->param('wx_login_code', '');
        $weSession   = WeMiniService::getWeLoginSession($wxLoginCode);
        if (empty($mobile) || !preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            $this->error('请输入正确的手机号');
        }
        if ($zf_code === 'annual_card') {
            $user = HealthUser::getByMobile($mobile);
            if (!$user) { //未注册用户
                $user = $this->auth->register($mobile, $weSession['openid'] ?? '', $weSession['session_key'] ?? '', [
                    'scene'      => 'ztf',
                    'channel_id' => $pid,
                    'platform'   => $platform,
                    'url'        => $url,
                ]);
            } else {
                $user->openid      = $weSession['openid'] ?? '';
                $user->session_key = $weSession['session_key'] ?? '';
                $user->save();
            }
            // 创建请求记录
            $healthBusiness = HealthBusiness::create([
                'mobile'     => $mobile,
                'request_id' => $request_id,
                'zf_code'    => $zf_code,
                'status'     => 0,
                'channel'    => $pid,
                'platform'   => $platform,
                'ip'         => $this->request->ip(),
                'url'        => $url,
                'click_id'   => $clickid,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            //创建年卡订单
            $healthAnnualCardOrder = EquityCenterService::orderAnnualCard($mobile, MasterUser::getMasterUserId($mobile));
            if (empty($healthAnnualCardOrder['order_no'])) {
                $this->error('订单创建失败');
            }
            // 创建支付订单
            $payment    = HealthPayment::create([
                'type'            => 1,
                'user_id'         => $user['id'],
                'order_no'        => $healthAnnualCardOrder['order_no'],
                'pay_description' => $healthAnnualCardOrder['interests_name'],
                'pay_way'         => HealthPayment::PAY_WAY_WECHAT,
                'pay_money'       => $healthAnnualCardOrder['pay_money'],
                'pay_status'      => 0
            ]);
            $pay_config = HealthPayment::createdWechatPay($payment, $weSession['openid'] ?? '');
            if (empty($pay_config['prepay_id'])) {
                $this->error('微信支付创建失败');
            }
            $pay_config = WePayService::WePayOrder()->jsapiParams($pay_config['prepay_id']);
            $healthBusiness->save(['order_no' => $healthAnnualCardOrder['order_no']]);
            $this->success('success', [
                'pay_config' => $pay_config,
                'payment_id' => $payment['id'],
                'pay_status' => $payment['pay_status']
            ]);
        } else {
            if (empty($code)) {
                $this->error('请输入短信验证码');
            }
            if (empty($zf_code) || empty($city_code) || empty($order_no)) {
                $this->error('请求异常,请联系客服');
            }
            // 创建请求记录
            $healthBusiness = HealthBusiness::where('order_no', $order_no)->find();
            if (!$healthBusiness) {
                $healthBusiness = HealthBusiness::create([
                    'order_no'   => $order_no,
                    'request_id' => $request_id,
                    'mobile'     => $mobile,
                    'zf_code'    => $zf_code,
                    'code'       => $code,
                    'city'       => $city_code,
                    'status'     => 0,
                    'channel'    => $pid,
                    'platform'   => $platform,
                    'ip'         => $this->request->ip(),
                    'url'        => $url,
                    'click_id'   => $clickid,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }
            $result = BusinessService::handle([
                'mobile'    => $mobile,
                'zf_code'   => $zf_code,
                'city_code' => $city_code,
                'ip'        => $this->request->ip(),
                'code'      => $code,
                'order_no'  => $order_no,
                'platform'  => $platform,
                'url'       => $url,
                'click'     => $clickid
            ]);
            if ($result === true) {
                $user = HealthUser::getByMobile($mobile);
                if (!$user) { //未注册用户
                    $user = $this->auth->register($mobile, $weSession['openid'] ?? '', $weSession['session_key'] ?? '', [
                        'scene'      => 'ztf',
                        'channel_id' => $pid,
                        'platform'   => $platform,
                        'url'        => $url,
                    ]);
                } else {
                    $user->openid      = $weSession['openid'] ?? '';
                    $user->session_key = $weSession['session_key'] ?? '';
                    $user->save();
                }
                $this->auth->direct($user['id']);
                $data['userinfo'] = $this->auth->getUserinfo();
                $healthBusiness->save(['status' => 2]);
                $this->success('办理成功', $data);
            }
            HealthBusinessAccess::where('request_id', $request_id)->update([
                'status' => -1
            ]);
            $healthBusiness->save(['status' => -1, 'error' => $result]);
            $this->error($result);
        }
        $this->error('非法请求');
    }

    /**
     * 业务办理回调
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function business_notify(): string
    {
        $params = $this->request->param();
        if (empty($params['order_no']) || empty($params['mobile']) || empty($params['zfCode'])) {
            return 'FAIl';
        }
        $healthBusiness = HealthBusiness::where('order_no', $params['order_no'])
            ->where('mobile', $params['mobile'])
            ->where('zf_code', $params['zfCode'])
            ->find();
        if (!$healthBusiness) {
            return 'FAIl';
        }
        if ($params['status'] == 0) {
            HealthBusinessAccess::where('request_id', $healthBusiness['request_id'])->update([
                'status' => 2
            ]);
            $healthBusiness->save(['status' => 2]);
        } else {
            HealthBusinessAccess::where('request_id', $healthBusiness['request_id'])->update([
                'status' => -1
            ]);
            $healthBusiness->save(['status' => -1, 'error' => $params['msg'] ?? '-']);
        }
        return 'SUCCESS';
    }

    /**
     * 发送业务办理短信
     * @Author 张旭鹏
     * @DateTime 2023-07-06
     */
    public function send_code(): void
    {
        $mobile = $this->request->param('mobile', $this->auth ? $this->auth->mobile : '');
        $city   = $this->request->param('city');
        $zfCode = $this->request->param('zfCode');
        $isVip  = EquityCenterService::isPajkVip($mobile);
        if ($isVip) {
            $this->error('您已办理业务,请到我的权益使用');
        }
        if ($this->auth && (time() - $this->auth->created_at) < 300) {
            $this->error('系统核验中,请稍后查看');
        }
        if (empty($city)) {
            $this->error('请输入城市CODE');
        }
        if (empty($zfCode)) {
            $this->error('请输入业务代码');
        }
        $sendCode = EquityCenterService::sendCode($mobile, $city, $zfCode);
        if (isset($sendCode['error_code'])) {
            $this->error($sendCode['msg']);
        }
        $this->success('成功', $sendCode);
    }

    /**
     * 领取健身礼包
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function fitness(): void
    {
        $isVip = EquityCenterService::isPajkVip($this->auth->mobile);
        if ($isVip === 0) {
            $this->error('请办理会员');
        }
        $isGet = Cache::store('redis')->get('equity:fitness:' . $this->auth->mobile);
        if ($isGet) {
            $this->error('礼包已领取');
        }
        Cache::store('redis')->set('equity:fitness:' . $this->auth->mobile, 1, TimeHelper::secondEndMonth());
        $this->success('领取成功');
    }

    /**
     * 获取健身礼包领取状态
     * @return void
     */
    public function fitness_status(): void
    {
        $isGet = Cache::store('redis')->get('equity:fitness:' . $this->auth->mobile);
        $this->success('success', ['is_get' => $isGet ? 1 : 0]);
    }


    /**
     * 获取泛渠道-用户的代金券数据
     * @return void
     * @throws DbException
     */
    public function wechat_coupons()
    {
        $paginate = CouponSend::where('mobile', $this->auth->mobile)
            ->with(['store'])
            ->field('id,store_id,stock_name,description,status,distr_month')
            ->where('distr_month', date('Y-m'))
            ->paginate($this->request->param('limit/d', 10))
            ->each(function ($item) {
                $item->append(['status_txt']);
            });
        $this->success('', $paginate);
    }
}
